package com.cxyjy.travelguide.controller;

import com.aliyun.tea.TeaException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/v1")
public class CreateIndex {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static String workSpaceId;
    @Value("${dashscope.work-space-id}")
    public void setWorkSpaceId(String id) {
        CreateIndex.workSpaceId = id;
    }
    private static String accessKeyId;
    @Value("${dashscope.access-key-id}")
    public void setAccessKeyId(String id) {
        CreateIndex.accessKeyId = id;
    }
    private static String accessKeySecret;
    @Value("${dashscope.access-key-secret}")
    public void setAccessKeySecret(String id) {
        CreateIndex.accessKeySecret = id;
    }

    public static com.aliyun.bailian20231229.Client createClient() throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config();
        // 凭证类型。
        credentialsConfig.setType("access_key");
        // 设置为AccessKey ID值。
//        System.out.println(workSpaceId+" "+accessKeyId+":"+accessKeySecret);
        credentialsConfig.setAccessKeyId(accessKeyId);
        // 设置为AccessKey Secret值。
        credentialsConfig.setAccessKeySecret(accessKeySecret);
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credentialClient);
        // Endpoint 请参考 https://api.aliyun.com/product/bailian
        config.endpoint = "bailian.cn-beijing.aliyuncs.com";
//        System.out.println("create client ok");
        return new com.aliyun.bailian20231229.Client(config);
    }

    public static com.aliyun.teaopenapi.models.Params createApiInfo_CreateIndex(String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("CreateIndex")
                // 接口版本
                .setVersion("2023-12-29")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接口 PATH
                .setPathname("/" + WorkspaceId + "/index/create")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    public static com.aliyun.teaopenapi.models.Params createApiInfo_SubmitIndexJob(String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("SubmitIndexJob")
                // 接口版本
                .setVersion("2023-12-29")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接口 PATH
                .setPathname("/" + WorkspaceId + "/index/submit_index_job")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    @PostMapping("/repository-create-index")
    public String createIndex(@RequestBody Map<String, Object> request) throws Exception {
        //检查输入：必选常见知识库所需字段：name
        String name = request.get("name").toString();
        if (name==null || name.isEmpty())
        {
            System.err.println("消息格式不合法，请使用默认列表");
            ObjectNode response = objectMapper.createObjectNode();
            response.put("code", 304); //
            response.put("msg", "错误原因：缺少创建的知识库名称！");
            ObjectNode data = objectMapper.createObjectNode();
            response.set("data", data);
            return response.toString();
        }

        com.aliyun.teaopenapi.Client client = CreateIndex.createClient();
        com.aliyun.teaopenapi.models.Params params = CreateIndex.createApiInfo_CreateIndex(workSpaceId);
        //配置请求
        java.util.Map<String, Object> queries = new java.util.HashMap<>();
        queries.put("Name", name);
        queries.put("StructureType", "unstructured");
        queries.put("SourceType", "DATA_CENTER_CATEGORY");
        queries.put("DocumentIds", "[\"\"]");
        queries.put("CategoryIds", "[\"\"]");
        queries.put("SinkType", "BUILT_IN");
        queries.put("Description", name);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest aliRequest = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setQuery(com.aliyun.openapiutil.Client.query(queries));

        String indexId;
        try {
            Map<String,?> createIndexResponse = client.callApi(params, aliRequest, runtime);
            Map<String, ?> body = (Map<String, ?>) createIndexResponse.get("body");
            // 1. 检查响应是否有效
            String httpStatus = body.get("Status").toString();
            if (!Objects.equals(httpStatus, "200")) {
                System.err.println("请求失败");
                ObjectNode response = objectMapper.createObjectNode();
                response.put("code", 304);
                if (body.get("Code").equals("Index.IndexNameAlreadyExists")) response.put("msg", "错误原因：已有相同名称的知识库，请检查创建知识库的名称！");
                else response.put("msg", "错误原因："+body.get("Message"));
                ObjectNode data = objectMapper.createObjectNode();
                response.set("data", data);
                return response.toString();
            }
            // 2. 获取Data字段
            Map<String,String> responseData = (Map<String,String>) body.get("Data");

            if (responseData == null) {
                System.err.println("请求失败");
                ObjectNode response = objectMapper.createObjectNode();
                response.put("code", 304); //
                response.put("msg", "错误原因："+body.get("Message"));
                ObjectNode data = objectMapper.createObjectNode();
                response.set("data", data);
                return response.toString();
            }
            // 3. 提取Id
            indexId = responseData.get("Id");
            System.out.println("成功创建索引，ID: " + indexId);
            ObjectNode response = objectMapper.createObjectNode();
            response.put("code", 200); //
            response.put("msg", "创建成功");
            ObjectNode data = objectMapper.createObjectNode();
            data.put("IndexId", indexId);
            response.set("data", data);
            return response.toString();

        } catch (TeaException error) {
            System.err.println("请求失败");
            ObjectNode response = objectMapper.createObjectNode();
            response.put("code", 300); //
            response.put("msg", "错误原因："+error.getMessage());
            ObjectNode data = objectMapper.createObjectNode();
            response.set("data", data);
            return response.toString();
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.err.println("请求失败");
            ObjectNode response = objectMapper.createObjectNode();
            response.put("code", 300); //
            response.put("msg", "可能错误原因："+error.getMessage());
            ObjectNode data = objectMapper.createObjectNode();
            response.set("data", data);
            return response.toString();
        }
    }
}
